package com.yum.ms.mq;

import com.alibaba.fastjson.JSON;
import com.yum.ms.entity.SeckillMessage;
import com.yum.ms.entity.SeckillOrder;
import com.yum.ms.entity.User;
import com.yum.ms.entity.vo.GoodsVO;
import com.yum.ms.service.IGoodsService;
import com.yum.ms.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Yum
 * @version 1.0
 * 消息接收者
 */
@Service
@Slf4j
public class MQReceive {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;
    /**
     * 接收消息，做下单处理
     * @param message
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        SeckillMessage seckillMessage = JSON.parseObject(message,SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodId = seckillMessage.getGoodId();
        // 数据库
        // 判断库存
        GoodsVO goodsVO = goodsService.selectGoodsVOById(goodId);
        if(goodsVO.getStockCount()<1) {
            return;
        }
        // redis操作
        // 判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder)redisTemplate.opsForValue().get("order:" + user.getId() +":"+ goodId);
        if(seckillOrder != null) {
            return;
        }
        // 真正下单
        orderService.seckill(user,goodsVO);
        log.info("接收消息：{}",message);
    }

}
